function [B,Tols,Tnwest,AR2]=myols(X,Y,lag)

idx=all(isfinite(X),2) & isfinite(Y);
X=X(idx,:); Y=Y(idx);

[T,K]=size(X);
B=X\Y; E=Y-X*B;
r2=1-var(E)/var(Y);
AR2=(1-K)/(T-K)+(T-1)*r2/(T-K);
Q=inv(X'*X);
s=E'*E/(T-K);
V_ols=s*Q;

%lag=12;
XE=X.*E(:,ones(K,1));
V_nwest=XE'*XE;
for i=1:lag
    XEt=XE(1:T-i,:);
    XEt_i=XE(1+i:T,:);
    xx=XEt'*XEt_i;
    V_nwest=V_nwest+(1-i/(lag+1))*(xx+xx');
end
V_nwest=Q*V_nwest*Q*T/(T-K);

Tols=B./sqrt(diag(V_ols));
Tnwest=B./sqrt(diag(V_nwest));
return